package site.wetsion.galio.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import site.wetsion.galio.auth.filter.AuthorizeFilter;
import site.wetsion.galio.data.service.UserService;

/**
 * web安全配置类
 *
 * @author weixin
 * @version 1.0
 * @CLassName WebSecurityCongfig
 * @date 2019/3/6 11:46 AM
 */
@Primary
@Configuration
public class WebSecurityCongfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService rmsUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/oauth/**", "/login")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/authorize").authenticated()
                .and()
                .addFilterBefore(
                        new AuthorizeFilter("/oauth/authorize",
                                authenticationManager(),
                                userService),
                        UsernamePasswordAuthenticationFilter.class)
        ;
    }

    @Autowired
    private UserService userService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(rmsUserDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Bean
    public PasswordEncoder noopPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
